<template>
  <el-card class="trend-chart-card" shadow="hover">
    <template #header>
      <div class="chart-header">
        <h3>{{ title }}</h3>
        <el-radio-group v-model="chartType" size="small">
          <el-radio-button value="new">新增数据</el-radio-button>
          <el-radio-button value="total">总量数据</el-radio-button>
          <el-radio-button value="active">活跃数据</el-radio-button>
        </el-radio-group>
      </div>
    </template>
    <div ref="chartRef" class="chart-container" />
  </el-card>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, nextTick } from "vue";
import * as echarts from "echarts";
import type { GrowthTrendStats } from "@/api/dashboard";

interface Props {
  /** 图表标题 */
  title: string;
  /** 趋势数据 */
  data: GrowthTrendStats | null;
  /** 加载状态 */
  loading?: boolean;
}

const props = withDefaults(defineProps<Props>(), {
  loading: false
});

const chartRef = ref<HTMLElement>();
const chartType = ref<"new" | "total" | "active">("new");
let chartInstance: echarts.ECharts | null = null;

// 初始化图表
const initChart = () => {
  if (!chartRef.value) return;

  chartInstance = echarts.init(chartRef.value);
  updateChart();
};

// 更新图表数据
const updateChart = () => {
  if (!chartInstance || !props.data) return;

  const { dates } = props.data;
  let series: any[] = [];

  // 根据图表类型选择数据
  switch (chartType.value) {
    case "new":
      series = [
        {
          name: "新增用户",
          type: "line",
          data: props.data.userTrend,
          smooth: true,
          symbol: "circle",
          symbolSize: 6,
          lineStyle: { width: 3 },
          itemStyle: { color: "#409EFF" },
          areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: "rgba(64, 158, 255, 0.3)" },
              { offset: 1, color: "rgba(64, 158, 255, 0.1)" }
            ])
          }
        },
        {
          name: "新增文章",
          type: "line",
          data: props.data.articleTrend,
          smooth: true,
          symbol: "circle",
          symbolSize: 6,
          lineStyle: { width: 3 },
          itemStyle: { color: "#67C23A" },
          areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: "rgba(103, 194, 58, 0.3)" },
              { offset: 1, color: "rgba(103, 194, 58, 0.1)" }
            ])
          }
        },
        {
          name: "新增评论",
          type: "line",
          data: props.data.commentTrend,
          smooth: true,
          symbol: "circle",
          symbolSize: 6,
          lineStyle: { width: 3 },
          itemStyle: { color: "#E6A23C" },
          areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: "rgba(230, 162, 60, 0.3)" },
              { offset: 1, color: "rgba(230, 162, 60, 0.1)" }
            ])
          }
        }
      ];
      break;
    case "total":
      series = [
        {
          name: "用户总数",
          type: "line",
          data: props.data.totalUserTrend,
          smooth: true,
          symbol: "circle",
          symbolSize: 6,
          lineStyle: { width: 3 },
          itemStyle: { color: "#409EFF" }
        },
        {
          name: "文章总数",
          type: "line",
          data: props.data.totalArticleTrend,
          smooth: true,
          symbol: "circle",
          symbolSize: 6,
          lineStyle: { width: 3 },
          itemStyle: { color: "#67C23A" }
        },
        {
          name: "评论总数",
          type: "line",
          data: props.data.totalCommentTrend,
          smooth: true,
          symbol: "circle",
          symbolSize: 6,
          lineStyle: { width: 3 },
          itemStyle: { color: "#E6A23C" }
        }
      ];
      break;
    case "active":
      series = [
        {
          name: "活跃用户",
          type: "line",
          data: props.data.activeUserTrend,
          smooth: true,
          symbol: "circle",
          symbolSize: 6,
          lineStyle: { width: 3 },
          itemStyle: { color: "#F56C6C" },
          areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: "rgba(245, 108, 108, 0.3)" },
              { offset: 1, color: "rgba(245, 108, 108, 0.1)" }
            ])
          }
        }
      ];
      break;
  }

  const option = {
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "cross",
        label: {
          backgroundColor: "#6a7985"
        }
      }
    },
    legend: {
      data: series.map(s => s.name),
      bottom: 0
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "15%",
      containLabel: true
    },
    xAxis: {
      type: "category",
      boundaryGap: false,
      data: dates,
      axisLabel: {
        formatter: (value: string) => {
          const date = new Date(value);
          return `${date.getMonth() + 1}/${date.getDate()}`;
        }
      }
    },
    yAxis: {
      type: "value",
      axisLabel: {
        formatter: (value: number) => {
          if (value >= 1000) {
            return `${(value / 1000).toFixed(1)}k`;
          }
          return value.toString();
        }
      }
    },
    series
  };

  chartInstance.setOption(option, true);
};

// 监听图表类型变化
watch(chartType, () => {
  updateChart();
});

// 监听数据变化
watch(
  () => props.data,
  () => {
    updateChart();
  },
  { deep: true }
);

// 监听加载状态
watch(
  () => props.loading,
  loading => {
    if (chartInstance) {
      if (loading) {
        chartInstance.showLoading();
      } else {
        chartInstance.hideLoading();
      }
    }
  }
);

onMounted(() => {
  nextTick(() => {
    initChart();
  });
});

// 响应式处理
const handleResize = () => {
  if (chartInstance) {
    chartInstance.resize();
  }
};

onMounted(() => {
  window.addEventListener("resize", handleResize);
});

// 组件卸载时清理
import { onBeforeUnmount } from "vue";
onBeforeUnmount(() => {
  if (chartInstance) {
    chartInstance.dispose();
  }
  window.removeEventListener("resize", handleResize);
});
</script>

<style scoped>
/* 响应式设计 */
@media (width <= 768px) {
  .chart-header {
    flex-direction: column;
    gap: 12px;
    align-items: flex-start;
  }

  .trend-chart-card {
    height: 450px;
  }

  .chart-container {
    height: 350px;
  }
}

.trend-chart-card {
  height: 400px;
  border-radius: 12px;
}

.chart-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.chart-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.chart-container {
  width: 100%;
  height: 300px;
}
</style>
